package com.gardenguell.salad.data.volley;

import com.android.volley.*;
import com.gardenguell.salad.app.AppConstant;
import com.gardenguell.salad.util.CommonLog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * Volley adapter for JSON requests that will be parsed into Java objects by Gson.
 */
public class GsonRequest<T> extends Request<T> {

    private static final CommonLog log = CommonLog.getInstance();

    /** Default charset for JSON request. */
    protected static final String PROTOCOL_CHARSET = "utf-8";

    /** Content type for request. */
    private static final String PROTOCOL_CONTENT_TYPE =
            String.format("application/json; charset=%s", PROTOCOL_CHARSET);

    private final Gson gson;
    private final Type type;
    private final Map<String, String> headers;
    private final Listener<T> listener;
    private final String mRequestBody;

    public GsonRequest(int method, String url, Type type, Map<String, String> headers, String requestBody,
                       Listener<T> listener, ErrorListener errorListener){
        super(method, url, errorListener);
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        gson = gsonBuilder.create();
        this.type = type;
        this.headers = headers;
        this.listener = listener;
        this.mRequestBody = requestBody;
    }

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url URL of the request to make
     * @param type Relevant class object, for Gson's reflection
     * @param headers Map of request headers
     */
    public GsonRequest(String url, Type type, Map<String, String> headers,
                       Listener<T> listener, ErrorListener errorListener) {
        this(Method.GET, url, type, headers, null, listener, errorListener);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }


    @Override
    protected void deliverResponse(T response) {
        // if response if null the response will not delivered!!
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data, HttpHeaderParser.parseCharset(response.headers));
            StringBuffer sb = new StringBuffer();
            sb.append(this.getMethod() == Request.Method.GET ? "GET; " : "POST; ");
            sb.append(this.getUrl() + "; ");
            try {
                if(this.getBody() != null) {
                    sb.append(new String(this.getBody(), "UTF-8"));
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sb.append(";" + json);
            log.d(AppConstant.LOG_TAG.NETWORK_RESPONSE + "--------->" + sb);
            T res = gson.fromJson(json, type);
            return Response.success(
                    res, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }

    @Override
    public byte[] getBody() {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }


}

